<template>
  <div class="mainua">
    <el-form
      class="demo-form-inline"
      :model="form"
      label-width="120px"
      ref="form"
    >
      <div class="main_spac1" style="padding-bottom: 5px">
        <div class="main_white padding10">
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>运费设置</span>
            </div>
          </div>
          <!-- 主要部分 -->
          <div class="marginTop20 marginLeft25">
            <el-form-item label="模板名称：" prop="name" :rules="rules.name">
              <el-input
                class="wid240"
                v-model="form.name"
                placeholder="模板名称"
                @change="isEdit = true"
              ></el-input>
            </el-form-item>
            <el-form-item prop="start_price">
              <div slot="label">
                起订金额<el-tooltip
                  class="item marginRight5 mainor_tei"
                  effect="dark"
                  placement="top"
                >
                  <div slot="content">
                    等于0调用系统订单配置，大于0调用本配置
                  </div>
                  <i class="el-icon-question"></i></el-tooltip
                >：
              </div>
              <el-input-number
                v-model.trim="form.start_price"
                :controls="false"
                :precision="2"
                :min="0"
                placeholder="起订金额"
                @change="isEdit = true"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              label="运费："
              prop="is_receive"
              :rules="rules.is_receive"
            >
              <el-radio-group v-model="form.is_receive" @change="isEdit = true">
                <el-radio :label="1">收运费</el-radio>
                <el-radio :label="0">不收运费</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 不收运费 -->
            <div v-show="form.is_receive == 0 && form.is_receive != null">
              <el-form-item>
                <p>绑定了该模板的用户，订单均不收取运费</p>
              </el-form-item>
            </div>
            <!-- 收运费 -->
            <div v-if="form.is_receive == 1">
              <el-form-item label="计算方式：" prop="type" :rules="rules.type">
                <el-radio-group v-model="form.type">
                  <el-radio :label="1">订单金额比例</el-radio>
                  <el-radio :label="2">订单金额区间</el-radio>
                  <el-radio :label="3">自动步进</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- 订单金额比例 -->
              <div v-if="form.type == 1">
                <el-form-item
                  label="订单金额比例："
                  prop="rate"
                  :rules="rules.rate"
                >
                  <el-input
                    class="wid140"
                    v-model.trim="form.rate"
                    placeholder="订单金额比例"
                  >
                    <template slot="append">%</template></el-input
                  >
                </el-form-item>

                <el-form-item prop="name">
                  <span slot="label">免运费规则:</span>

                  订单金额超过（含）<el-input-number
                    style="margin-right: 8px"
                    v-model="form.free"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元，免运费（0或不填则不免)
                </el-form-item>
              </div>
              <!-- 订单金额区间 -->
              <div v-show="form.type == 2">
                <el-form-item label="" prop="name">
                  <span slot="label">订单金额:</span>
                  <div
                    class="rule"
                    v-for="(item, index) in rule_list_type2"
                    :key="index"
                  >
                    <el-input-number
                      v-model="item.start"
                      :controls="false"
                      :min="item.min_start"
                      :precision="2"
                    ></el-input-number>
                    元，至
                    <el-input-number
                      v-model="item.end"
                      :min="item.start + 1"
                      :controls="false"
                      :precision="2"
                    ></el-input-number>
                    元（不包含），运费
                    <el-input-number
                      v-model="item.fee"
                      :min="item.min_free"
                      :controls="false"
                      :precision="2"
                    ></el-input-number
                    >元
                    <span class="rule_delete" v-if="index != 0"
                      ><i class="el-icon-close" @click="reduceRules(index)"></i
                    ></span>
                  </div>
                  <div class="rule" style="margin-left: 8px">
                    <el-button
                      type="primary"
                      @click="addRules"
                      :class="{ addrule_btn: rule_list_type2.length >= 3 }"
                    >
                      <i class="el-icon-plus"></i>
                      添加运费金额规则
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item prop="free_type2">
                  <span slot="label">免运费规则:</span>
                  订单金额超过（含）<el-input-number
                    style="margin-right: 8px"
                    v-model.trim="form.free_type2"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元，免运费（0或不填则不免)
                </el-form-item>
              </div>
              <!-- 自动步进 -->
              <div v-show="form.type == 3">
                <el-form-item prop="name">
                  <span slot="label">订单金额小于:</span>
                  <el-input-number
                    style="margin-right: 8px"
                    v-model.trim="rule_list_type3.base_money"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元，运费
                  <el-input-number
                    style="margin-right: 8px"
                    v-model.trim="rule_list_type3.base_fee"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元
                </el-form-item>
                <el-form-item prop="name">
                  <span slot="label">订单金额每满:</span>
                  <el-input-number
                    style="margin-right: 8px"
                    v-model.trim="rule_list_type3.once_money"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元，运费加收
                  <el-input-number
                    style="margin-right: 8px"
                    v-model.trim="rule_list_type3.fee"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元
                </el-form-item>
                <el-form-item prop="free_type2">
                  <span slot="label">免运费规则:</span>

                  订单金额超过（含）<el-input-number
                    style="margin-right: 8px"
                    v-model.trim="rule_list_type3.free"
                    :controls="false"
                    :precision="2"
                  ></el-input-number
                  >元，免运费（0或不填则不免)
                </el-form-item>
              </div>
            </div>
            <el-form-item label="描述：" prop="remark">
              <div style="width: 360px">
                <el-input
                  class="wid240"
                  v-model="form.remark"
                  placeholder="描述"
                  type="textarea"
                  @change="isEdit = true"
                ></el-input>
              </div>
            </el-form-item>
          </div>

          <div class="clearfix"></div>
          <div class="paddingBottom10" id="newConBox">
            <div class="newConBox_h32">
              <div :class="['boxdq newConBox ', { on: searchBarFixed }]">
                <div class="mainor_prl">
                  <el-button
                    type="primary"
                    @click="handlePreserve"
                    v-repeatClick
                    :loading="saveLoading"
                    >保存</el-button
                  >
                  <el-button
                    class="reset marginLeft10"
                    type="info"
                    v-repeatClick
                    @click="handleCancel"
                    >取消</el-button
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import { delivery_info, delivery_edit } from "@/api/user/userFreight";
import rules from "@/rules/user/userFreight";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";
export default {
  name: "",
  data() {
    return {
      rules,
      form: {
        name: "",
        start_price:0,
        type: "", //计算方式 1订单金额比例   2订单金额区间 3自动步进
        is_receive: 1, //是否收运费 0  不收  1收
        remark: "",
        rate: 0,
        free: 0,
        free_type2: 0,
      },

      // 监听滚动
      searchBarFixed: false,
      rule_list_type2: [
        {
          start: 0,
          end: 0,
          fee: 0,
          min_start: 0,
          min_end: 0,
          min_free: 0,
        },
      ],
      rule_list_type3: {
        base_money: 0,
        base_fee: 0,
        once_money: 0,
        fee: 0,
        free: 0,
      },
      id: "",
      saveLoading: false,
      isEdit: false,
    };
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 240
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },

    /* ----  订单金额区间  ---- */
    // 添加规则
    addRules() {
      this.isEdit = true;
      let length = this.rule_list_type2.length;
      if (this.rule_list_type2.length < 3) {
        this.rule_list_type2.push({
          start: this.rule_list_type2[length - 1].end + 0.01,
          end: this.rule_list_type2[length - 1].end + 0.01,
          fee: this.rule_list_type2[length - 1].fee,
          min_start: this.rule_list_type2[length - 1].end + 0.01,
          min_end: this.rule_list_type2[length - 1].end + 0.01,
          min_free: 0,
        });
      } else {
        return;
      }
    },
    // 减少规则
    reduceRules(index) {
      this.rule_list_type2.splice(index, 1);
    },
    /* ----  订单金额区间  ---- */
    handleCancel() {
      this.isEdit = false;
      this.$router.back(-1);
    },
    // 保存
    handlePreserve() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let response = this.handleData();
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            { ...response },
            { id: this.id }
          );
          this.saveLoading = true;
          delivery_edit(data).then((res) => {
            this.saveLoading = false;
            if (res.errcode == 0) {
              this.$message.success("编辑成功");
              this.isEdit = false;
              this.$router.back(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    // 处理数据
    handleData() {
      let form = JSON.parse(JSON.stringify(this.form));
      let rule_list_type2 = JSON.parse(JSON.stringify(this.rule_list_type2));
      let rule_list_type3 = JSON.parse(JSON.stringify(this.rule_list_type3));
      let new_form = {
        name: form.name,
        is_receive: form.is_receive,
        start_price: form.start_price,
        type: form.type,
        remark: form.remark,
        rule: "",
      };
      let list = {};
      switch (form.type) {
        case 1:
          list.free = form.free;
          list.rate = form.rate;
          break;
        case 2:
          let rule_data = rule_list_type2.map((e) => {
            let { min_end, min_free, min_start, ...sz } = e;
            return sz;
          });
          list.rule_data = rule_data;
          list.free = form.free_type2;
          break;
        case 3:
          list = rule_list_type3;
          break;
        default:
          new_form.type = 0;
          delete new_form.rule;
          break;
      }
      if (form.is_receive) {
        if (String(list.free) == "" || list.free == undefined) {
          list.free = 0;
          return;
        }
        new_form.rule = list;
        new_form.rule = JSON.stringify(new_form.rule);
      }

      return new_form;
    },
    // 模板信息
    delivery_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      delivery_info(data).then((res) => {
        if (res.errcode == 0) {
          let info = res.data.info;
          this.form.name = info.name;
          this.form.is_receive = info.is_receive;
          this.form.start_price = info.start_price;
          this.form.type = info.type;
          this.form.remark = info.remark;
          let rule = JSON.parse(info.rule);
          switch (info.type) {
            case 1:
              this.form.free = rule.free;
              this.form.rate = rule.rate;
              break;
            case 2:
              this.form.free_type2 = rule.free;
              let list = rule.rule_data.map((e, index) => {
                return {
                  start: e.start,
                  end: e.end,
                  fee: e.fee,
                  min_start: 0,
                  min_end: 0,
                  min_free: 0,
                };
              });
              this.rule_list_type2 = list;
              break;
            case 3:
              this.rule_list_type3.base_money = rule.base_money;
              this.rule_list_type3.base_fee = rule.base_fee;
              this.rule_list_type3.once_money = rule.once_money;
              this.rule_list_type3.fee = rule.fee;
              this.rule_list_type3.free = rule.free;
              break;

            default:
              break;
          }
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  created() {
    if (this.$route.params) {
      this.id = this.$route.params.id;
    }
    this.delivery_info();
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
    let scrollTop =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop;

    scrollTop + document.documentElement.clientHeight >
    document.getElementById("newConBox").offsetTop + 50
      ? (this.searchBarFixed = false)
      : (this.searchBarFixed = true);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>
<style lang='scss' scoped>
.validity {
  display: flex;
  align-items: center;
  flex-direction: row;
  &:first-child {
    margin-bottom: 18px;
  }
  /deep/ .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
  /deep/ .el-radio {
    margin-right: 10px;
    transform: translateY(1px);
  }
  span {
    font-size: 14px;
    color: #606266;
    display: inline-block;
    // padding-left: 15px;
    &.span1 {
      padding-left: 15px;
      padding-right: 10px;
    }
    &.span2 {
      padding-left: 10px;
    }
  }
}
.limit_number {
  margin: 0 10px;
}
.save_container {
  padding: 0 20px;
  margin-top: 15px;
  &.positive {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 9999;
  }
}
#newConBox {
  margin-top: 15px;
  padding-left: 20px;
}
.newConBox.on {
  margin-left: -10px;
  padding-left: 10px;
  bottom: 70px;
  border-top: 0;
  width: auto;
}
.goods_container_header {
  display: flex;
  align-items: flex-start;
  .btns {
    padding-left: 10px;
  }
}
.goods_container {
  height: 500px;
}
// 满减规则
.rule {
  display: flex;
  align-items: center;
  &:not(:first-child) {
    margin-top: 10px;
  }
  /deep/.el-input-number {
    width: 80px;
    margin: 0 8px;
  }
  .rule_delete {
    font-size: 20px;
    font-weight: 900;
    margin-left: 15px;
  }
  .addrule_btn {
    cursor: not-allowed;
    background-color: #ebebeb;
    border-color: #ebebeb;
    color: #606266;
  }
}
</style>
